import { Square } from "./Square";
import { Point, Shape } from "./types";

export class SquareGroup {
  // 方块组合体
  private _squares: readonly Square[] = [];

  public get squares() {
    return this._squares;
  }

  public get shape() {
    return this._shape;
  }

  public get centerPoint(): Point {
    return this._centrerPoint;
  }

  public set centerPoint(val: Point) {
    this._centrerPoint = val;
    // 同时更新所有小方块的坐标
    this.setSquarePoints();
  }

  /**
   * 根据中心点和形状，设置每一个小方块的坐标
   */
  private setSquarePoints() {
    this._squares.forEach((sq, i) => {
      sq.point = {
        x: this._shape[i].x + this._centrerPoint.x,
        y: this._shape[i].y + this._centrerPoint.y,
      };
    });
  }

  constructor(
    private _shape: Shape,
    private _centrerPoint: Point,
    private _color: string
  ) {
    const arr: Square[] = [];
    this._shape.forEach((p) => {
      const sq = new Square();
      sq.color = this._color;
      sq.point = {
        x: p.x + this._centrerPoint.x,
        y: p.y + this._centrerPoint.y,
      };
      arr.push(sq);
    });
    this._squares = arr;
  }

  /**
   * 旋转方向是否为顺时针
   */
  private _isClock = true;

  public get isClock(): boolean {
    return this._isClock;
  }

  public set isClock(val: boolean) {
    this._isClock = val;
  }

  afterRotateShape(): Shape {
    if (this._isClock) {
      return this._shape.map((p) => {
        const newP: Point = {
          x: -p.y,
          y: p.x,
        };
        return newP;
      });
    } else {
      return this._shape.map((p) => {
        const newP: Point = {
          x: p.y,
          y: -p.x,
        };
        return newP;
      });
    }
  }

  rotate() {
    const newShape = this.afterRotateShape();
    this._shape = newShape;
    // 同时更新所有小方块的坐标
    this.setSquarePoints();
  }
}
